package com.mjlf.mjatis.core;

import com.alibaba.fastjson.JSONObject;
import com.mjlf.mjatis.config.Configuration;
import com.mjlf.mjatis.exception.DataSourceException;
import com.mjlf.mjatis.excutor.DefaultExecutor;
import com.mjlf.mjatis.excutor.Executor;
import lombok.Data;
import lombok.extern.java.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @ClassName DefaultSqlSessionFactory
 * @Author mjlft
 * @Date 2020/5/26 23:18
 * @Version 1.0
 * @Description 默认SqlSession构造工厂类
 * 其实它主要负责的还是进行configuration配置解析， 然后生成SqlSession的工作
 * 当然对于Configuration的解析，这对不同类型的解析， 我们可以将其进行指派不同的工作者去完成、
 * <p>
 * 待完成
 */
@Data
@Log
public class DefaultSqlSessionFactory extends AbstractSqlSessionFactory {

    public Configuration parseConfiguration(InputStream inputStream) throws IOException {
        if (inputStream != null) {
            BufferedReader bufferedReader = null;
            try {
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuffer stringBuffer = new StringBuffer();
                String str = null;
                while ((str = bufferedReader.readLine()) != null){
                    stringBuffer.append(str);
                }
                JSONObject jsonObject = JSONObject.parseObject(stringBuffer.toString());
                //正常拿到Json配置
                Configuration configuration = new Configuration();

                //调用configuration的解析方法，首选需要将json对象转换为类对象存储
                configuration.parse(jsonObject);

                return configuration;
            } finally {
                try {
                    inputStream.close();
                    if (bufferedReader != null) {
                        bufferedReader.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public Configuration parseConfiguration(String basePath) {
        return null;
    }

    public Configuration parseConfiguration(String basePaht, InputStream inputStream) {
        return null;
    }

    /**
     * 解析configuration, 然后生成SqlSession
     *
     * @param configuration
     * @return
     */
    public SqlSession buildSqlSession(Configuration configuration) {
        SqlSession sqlSession = new DefaultSqlSession();
        sqlSession.setConfiguration(configuration);

        //创建Excutor
        Executor executor = new DefaultExecutor();
        configuration.setExecutor(executor);

        //首先进行parse解析
        return sqlSession;
    }
}
